
import os
import tkinter as tk
from tkinter import filedialog, messagebox
import pandas as pd

class XlsCsvToLuaConverter:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("XLS/CSV转LUA转换器")
        self.root.geometry("600x220")
        
        self.setup_ui()
        
    def setup_ui(self):
        # 主容器
        main_frame = tk.Frame(self.root, padx=20)
        main_frame.pack(fill=tk.BOTH, expand=True, pady=10)
        
        # 输入路径部分
        input_frame = tk.Frame(main_frame)
        input_frame.pack(fill=tk.X, pady=(10,0))
        
        # 红色提示文本（上方）
        hint_frame = tk.Frame(input_frame)
        hint_frame.pack(fill=tk.X)
        tk.Label(hint_frame, width=len("输入路径:")).pack(side=tk.LEFT)
        tk.Label(hint_frame, text="输入XLS/CSV文件的根目录", 
                fg="red", font=("Arial", 9), anchor="w").pack(side=tk.LEFT)
        
        # 输入路径标签和浏览按钮
        input_subframe = tk.Frame(input_frame)
        input_subframe.pack(fill=tk.X, pady=5)
        tk.Label(input_subframe, text="输入路径:").pack(side=tk.LEFT)
        self.input_entry = tk.Entry(input_subframe, width=40)
        self.input_entry.pack(side=tk.LEFT, padx=5, expand=True, fill=tk.X)
        tk.Button(input_subframe, text="浏览...", command=self.select_input).pack(side=tk.LEFT)
        
        # 输出路径部分
        output_frame = tk.Frame(main_frame)
        output_frame.pack(fill=tk.X, pady=(15,0))
        
        # 红色提示文本（上方）
        hint_frame_out = tk.Frame(output_frame)
        hint_frame_out.pack(fill=tk.X)
        tk.Label(hint_frame_out, width=len("输出路径:")).pack(side=tk.LEFT)
        tk.Label(hint_frame_out, text="输入LUA的输出目录", 
                fg="red", font=("Arial", 9), anchor="w").pack(side=tk.LEFT)
        
        # 输出路径标签和浏览按钮
        output_subframe = tk.Frame(output_frame)
        output_subframe.pack(fill=tk.X, pady=5)
        tk.Label(output_subframe, text="输出路径:").pack(side=tk.LEFT)
        self.output_entry = tk.Entry(output_subframe, width=40)
        self.output_entry.pack(side=tk.LEFT, padx=5, expand=True, fill=tk.X)
        tk.Button(output_subframe, text="浏览...", command=self.select_output).pack(side=tk.LEFT)
        
        # 确定按钮
        confirm_frame = tk.Frame(main_frame)
        confirm_frame.pack(side=tk.BOTTOM, pady=15, fill=tk.X)
        tk.Button(confirm_frame, text="确定", width=15, command=self.convert_to_lua).pack()
    
    def select_input(self):
        path = filedialog.askdirectory(title="选择输入文件夹")
        if path: 
            self.input_entry.delete(0, tk.END)
            self.input_entry.insert(0, path)
    
    def select_output(self):
        path = filedialog.askdirectory(title="选择输出文件夹")
        if path: 
            self.output_entry.delete(0, tk.END)
            self.output_entry.insert(0, path)
    
    def convert_to_lua(self):
        input_path = self.input_entry.get()
        output_path = self.output_entry.get()
        
        if not input_path or not output_path:
            messagebox.showerror("错误", "请选择输入和输出路径")
            return
        
        try:
            files = [f for f in os.listdir(input_path) if f.endswith(('.xls', '.xlsx', '.csv'))]
            if not files:
                messagebox.showwarning("警告", "输入路径中没有找到XLS/CSV文件")
                return
            
            for file in files:
                file_path = os.path.join(input_path, file)
                
                # 读取文件
                if file.endswith('.csv'):
                    df = pd.read_csv(file_path, header=None, skiprows=2)
                    comments = pd.read_csv(file_path, header=None, nrows=2)
                else:
                    df = pd.read_excel(file_path, header=None, skiprows=2)
                    comments = pd.read_excel(file_path, header=None, nrows=2)
                
                # 生成LUA内容
                lua_content = self.generate_lua(df, comments)
                
                # 保存文件
                lua_file = os.path.splitext(file)[0] + '.lua'
                lua_path = os.path.join(output_path, lua_file)
                
                with open(lua_path, 'w', encoding='utf-8') as f:
                    f.write(lua_content)
            
            messagebox.showinfo("完成", f"成功转换 {len(files)} 个文件")
            self.root.destroy()
            
        except Exception as e:
            messagebox.showerror("错误", f"转换过程中发生错误: {str(e)}")
    
    def generate_lua(self, df, comments):
        # 处理注释行
        lua_str = "-- 注释信息:\n"
        for _, row in comments.iterrows():
            lua_str += f"-- {row[0]}\n"
        
        # 处理表头
        headers = df.iloc[0].tolist()
        lua_str += "\nlocal data = {\n"
        
        # 处理数据行，以第一列为key
        for i in range(1, len(df)):
            row = df.iloc[i]
            key = self.format_lua_value(row[0])
            lua_str += f"    [{key}] = {{\n"
            # for j, val in enumerate(row[1:], start=1):
            for j, val in enumerate(row):
                header = headers[j] if j < len(headers) else f"col{j+1}"
                lua_str += f"        {header} = {self.format_lua_value(val)},\n"
            lua_str += "    },\n"
        
        lua_str += "}\n\nreturn data"
        return lua_str

    def format_lua_value(self, value):
        if pd.isna(value):
            return "nil"
        if isinstance(value, (int, float)):
            return str(value)
        return f'"{str(value)}"'

if __name__ == "__main__":
    app = XlsCsvToLuaConverter()
    app.root.mainloop()
